const {
  app,
  BrowserWindow,
  nativeImage,
  ipcMain,
  shell,
  dialog
} = require('electron')
const log = require('electron-log')
log.transports.file.level = 'info'
log.transports.console.level = false
log.info('App starting...');

const path = require('path')
const fs = require('fs')
const unzipper = require("unzipper");


const debug = /--debug/.test(process.argv[3]) || /--debug/.test(process.argv[2])

if (process.mas) app.setName('数据上报小工具')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
  // Create the browser window.
  const windowOptions = {
    width: 919,
    height: 621,
    fullScreen: false,
    resizable: false,
    title: app.getName(),
    show: false,
    frame: true, //有边框
    icon: nativeImage.createFromPath(`${__dirname}/resources/img/nzjxc.png`)
  }

  mainWindow = new BrowserWindow(windowOptions)
  mainWindow.once('ready-to-show', () => {
    mainWindow.show() //在加载页面时，渲染进程第一次完成绘制时，会发出 ready-to-show 事件 。 在此事件后显示窗口将没有视觉闪烁
    mainWindow.flashFrame(true)
    //mainWindow.setOverlayIcon(nativeImage.createFromPath(`${__dirname}/resources/img/nzjxc.png`),'ceshi')
  })
  //关闭引用菜单栏
  mainWindow.setMenuBarVisibility(false)
  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/app/login/html/login.html`)

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  if (debug) {
    mainWindow.webContents.openDevTools()
  }
  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  })
  //是否第一此进入登陆页面，是的话就进行版本检查
  let isFirst2LoginPage = true;
  ipcMain.on('readyCheckUpdate', function () {
    if (isFirst2LoginPage) {
      mainWindow.webContents.send('checkVersion')
    }
    isFirst2LoginPage = false;
  })
  //页面关闭
  ipcMain.on('send-cancel', (event, arg) => {
    mainWindow = null;
    app.quit();
  })
  let company = null;
  //登陆成功
  ipcMain.on('login-success', (event, arg) => {
    if (arg != null) {
      mainWindow.loadURL(`file://${__dirname}/app/main/html/index.html`);
      //发送消息
      company = arg;
    }
    //登录成功写文件
    mainWindow.setContentSize(1450, 900);
    mainWindow.center();
    mainWindow.setMaximizable(true);
    mainWindow.maximize();
    mainWindow.setResizable(true);
  })
  ipcMain.on('logout', (event, arg) => {
    user = null;
    mainWindow.setContentSize(913, 592);
    mainWindow.center();
    mainWindow.setMaximizable(false);
    mainWindow.loadURL(`file://${__dirname}/app/login/html/login.html`);
  })
  ipcMain.on('get-company-info', (event, arg) => {
    event.returnValue = company;
  })
  ipcMain.on('video-teaching', (event, url) => {
    shell.openExternal(url);

  })
  //主进程代码
  ipcMain.on('closed-message', (evt, args) => {
    mainWindow = null;
    app.quit();
  })
  //主进程下载文件
  let savePath; //文件保存在本地的路径
  ipcMain.on('download', (evt, args) => {
    let arr = args.split("+");
    let downPath = arr[0] //文件下载路径;
    savePath = arr[1];
    mainWindow.webContents.downloadURL(downPath);
  })

  ipcMain.on('download-zip', (evt, args) => {
    savePath = path.join(`${__dirname}`, 'app.zip');
    mainWindow.webContents.downloadURL(args);
  });
  mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
    // 设置保存路径,使Electron不提示保存对话框。
    if (savePath) {
      item.setSavePath(savePath);
    }

    item.on('updated', (event, state) => {
      if (state === 'interrupted') {
        console.log('Download is interrupted but can be resumed')
      } else if (state === 'progressing') {
        if (item.isPaused()) {
          console.log('Download is paused')
        } else {
          console.log(`Received bytes: ${item.getReceivedBytes()}`)
        }
      }
    })
    item.once('done', (event, state) => {
      if (state === 'completed') {
        if (savePath && savePath.indexOf('.zip') > 0) {
          let unzipExtractor = unzipper.Extract({
            path: `${__dirname}`
          });
          unzipExtractor.on('error', function (err) {
            log.error(err);
          });
          unzipExtractor.on('close', function () {
            mainWindow.webContents.send('unzipComplete');
          });
          fs.createReadStream(savePath).pipe(unzipExtractor);
        } else {
          dialog.showMessageBox({
            type: 'info',
            message: '文件下载已完成！'
          })
        }
        console.log('Download successfully')
      } else {
        dialog.showMessageBox({
          type: 'info',
          message: '文件下载失败！'
        })
        console.log(`Download failed: ${state}`)
      }
    })
  })

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})


// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
/**
 * 自动更新
 */
/* function checkUpdater() {
  autoUpdater.setFeedURL('http://192.168.1.108/')
  autoUpdater.autoDownload = false
  autoUpdater.autoInstallOnAppQuit = false //退出时自动安装更新程序
  autoUpdater.on('error', (e) => log.error(e))
  autoUpdater.on('checking-for-update', () => log.info('checking-for-update'))
  autoUpdater.on('update-available', (info) => {
    log.info('update-available', info)
    const options = {
      type: 'info',
      title: '提示',
      message: "系统检测到有新版本【" + info.version + "】，是否更新？",
      buttons: ['更新', '取消'],
      cancelId: 100
    }
    dialog.showMessageBox(options, function (index) {
      log.info('是否更新:', index)
      if (index === 0) {
        autoUpdater.downloadUpdate()
      }
    })
  })
  autoUpdater.on('update-not-available', (info) => log.info('update-not-available', info))

  // 更新下载进度事件
  autoUpdater.on('download-progress', (progressObj) => {
    let log_message = "Download speed: " + progressObj.bytesPerSecond;
    log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
    log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
    log.info(log_message)
    mainWindow.webContents.send('downloading', progressObj);
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    autoUpdater.quitAndInstall()
  })
} */